﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Knihotoc_WP8.Settings;

namespace Knihotoc_WP8.Pages
{
    public partial class CommonPlaceListPage : PhoneApplicationPage
    {
        private const double EARTH_RADIUS = 6378000;

        public CommonPlaceListPage()
        {
            this.InitializeComponent();
        }

        private double deg_to_rad(double deg)
        {
            return deg / (180 / Math.PI);
        }

        private double CalculateDistance(double lat1, double lon1, double lat2, double lon2)
        {
            return EARTH_RADIUS * Math.Acos(
                Math.Sin(lat1) * Math.Sin(lat2)
                + Math.Cos(lat1) * Math.Cos(lat2) * Math.Cos(lon2 - lon1));
        }

        private int CompareDistancesWithCurrentPosition(double lat1, double lon1, double lat2, double lon2)
        {
            double distance1 = CalculateDistance(CurrentSettings.Instance.CurrentPosition.Latitude,
                CurrentSettings.Instance.CurrentPosition.Longitude, lat1, lon1);
            double distance2 = CalculateDistance(CurrentSettings.Instance.CurrentPosition.Latitude,
                CurrentSettings.Instance.CurrentPosition.Longitude, lat2, lon2);

            return distance1.CompareTo(distance2);
        }        

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                base.OnNavigatedTo(e);
            }
            catch
            {
                // TODO
            }

            (ApplicationBar.Buttons[0] as ApplicationBarIconButton).Text = Localization.LocalizedStrings.Get("SettingsButtonLabel");
        }

        private void CommonPlaceItemTemplate_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/CommonPlaceDetailPage.xaml",
                UriKind.Relative));
        }

        private void SettingsApplicationBarButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/CommonPlaceListSettingsPage.xaml", UriKind.Relative));
        }
    }
}